<template>
  <el-table
    ref="tableRef"
    :data="tableData"
    row-key="id"
    border
    :height="tableHeight"
    style="width: 100%"
    v-bind="tableOption?.tableAttrs || {}"
    v-on="tableOption?.tableEvent || {}"
  >
    <el-table-column
      type="selection"
      v-if="tableOption?.selection"
      v-bind="selectionOption"
      align="center"
    />
    <el-table-column
      v-if="tableIndex"
      type="index"
      label="序号"
      fixed
      width="60"
      :index="indexMethod"
      align="center"
    />
    <el-table-column
      v-if="tableOption?.expand"
      type="expand"
    >
      <template #default="{ row, $index }">
        <slot
          name="expand"
          :row
          :index="$index"
        />
      </template>
    </el-table-column>
    <CustomColumn
      v-for="item in tableHeader"
      :key="item.id"
      :slotNames="slotNames"
      :column-item="item"
      :column-prop="item.prop"
    >
      <template
        v-for="slotItem in slotNames"
        :key="slotItem"
        #[slotItem]="{ row, index }"
      >
        <slot
          :name="slotItem"
          :index
          :row
        ></slot>
      </template>
    </CustomColumn>
  </el-table>
</template>

<script lang='ts' setup>
import { computed, reactive, ref } from 'vue';
import type { paginationType, tableHeaderType, tableOptionType } from '../TableType';
import CustomColumn from './CustomColumn.vue';

const props = defineProps<{
  tableHeader: tableHeaderType[]
  tableOption: tableOptionType
  paginationOption: paginationType
  slotNames: string[]
}>()

const tableRef = ref()

// 多选绑定属性
const selectionOption = computed(() => {
  return props.tableOption?.selectionOption ?? {}
})

// 是否显示索引
const tableIndex = computed(() => {
  return props.tableOption?.index !== false
})

// 分页配置
const pagination = reactive({
  page: 1,
  limit: 20
})

const setPagination = (page: number, limit: number) => {
  pagination.limit = limit
  pagination.page = page
}

// 自定义索引
const indexMethod = (index: number) => {
  return index + (pagination.page - 1) * pagination.limit + 1
}

const tableData = ref<any>([])

/**
 * 设置表格数据
 * @param data 表格数据
 */
const setTableData = (data: any[]) => {
  tableData.value = data
}

/**
 * 获取表格数据
 */
const getTableData = () => {
  return tableData.value
}

/**
 * 获取表格实例
 */
const getTableInstance = () => {
  return tableRef.value
}

// 表格高度
const tableHeight = ref("auto")
const setTableHeight = (height: number) => {
  tableHeight.value = height + 'px'
}

defineExpose({
  setTableHeight,
  setTableData,
  getTableData,
  getTableInstance,
  setPagination
})
</script>

<style scoped lang='scss'></style>